import { reqLogin } from "../../request/api"
import {myAlert} from "../../utils/alert"
//状态
const initState = {
    user: {
        phone: "",
        password: ""
    },
    //用户信息
    info:sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{} 
}

//action types
const TYPES = {
    //修改user的type
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    //修改info
    lOGIN_CHANGE_INFO:"lOGIN_CHANGE_INFO"
}

// action creators 
export const actions = {
    //修改user的action
    changeUser: (value, key) => ({ type: TYPES.LOGIN_CHANGE_USER, value, key }),
    //修改info
    changeInfo:(info)=>{
        //本地存储存一份
        if(info.uid){
            sessionStorage.setItem("info",JSON.stringify(info))
        }else{
            sessionStorage.removeItem("info")
        }
        return {type:TYPES.lOGIN_CHANGE_INFO,info}
    },
    //登陆请求
    reqLogin: (router) => {
        return (dispatch, getState) => {
            let { user } = getState().login;
            reqLogin(user).then(res => {
                //判断是否成功
                if (res.code === 200) {
                    //1.弹成功
                    myAlert(res.msg)
                    // 2.res.list存起来 本地存储存一份，redux存一份
                    dispatch(actions.changeInfo(res.list))
                    // 3.跳转页面
                    router.push("/index/home")
                }
            })
        }
    }
}

// reducer 
const reducer = (state = initState, action) => {
    switch (action.type) {
        //修改user
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            case TYPES.lOGIN_CHANGE_INFO:
            return {
                ...state,
                info:action.info
            }

        default:
            return state
    }
}

export default reducer
// selector 
//用户输入值
export const getUser = state => state.login.user;

//用户信息
export const getInfo=state=>state.login.info